import { ref, computed } from 'vue';
import { getHomeConfigs, getAboutConfigs, getContactConfigs, getGlobalConfigs, fetchSkills } from '/@/api/blog/config';

export interface BlogConfig {
  id: number;
  configKey: string;
  configValue: string;
  configType: 'string' | 'number' | 'boolean' | 'json' | 'text';
  description: string;
  pageType: 'home' | 'about' | 'contact' | 'global';
  sortOrder: number;
  status: number;
  createdTime: string;
  updatedTime: string;
}

export type ConfigMap = Record<string, any>;

export function useBlogConfig() {
  const homeConfigs = ref<BlogConfig[]>([]);
  const aboutConfigs = ref<BlogConfig[]>([]);
  const contactConfigs = ref<BlogConfig[]>([]);
  const globalConfigs = ref<BlogConfig[]>([]);
  const loading = ref(false);

  // 将配置数组转换为键值对映射
  const homeConfigMap = computed<ConfigMap>(() => {
    const map: ConfigMap = {};
    homeConfigs.value.forEach((config) => {
      if (config.configType === 'json') {
        try {
          map[config.configKey] = JSON.parse(config.configValue);
        } catch {
          map[config.configKey] = config.configValue;
        }
      } else {
        map[config.configKey] = config.configValue;
      }
    });
    return map;
  });

  const aboutConfigMap = computed<ConfigMap>(() => {
    const map: ConfigMap = {};
    aboutConfigs.value.forEach((config) => {
      if (config.configType === 'json') {
        try {
          map[config.configKey] = JSON.parse(config.configValue);
        } catch {
          map[config.configKey] = config.configValue;
        }
      } else {
        map[config.configKey] = config.configValue;
      }
    });
    return map;
  });

  const contactConfigMap = computed<ConfigMap>(() => {
    const map: ConfigMap = {};
    contactConfigs.value.forEach((config) => {
      if (config.configType === 'json') {
        try {
          map[config.configKey] = JSON.parse(config.configValue);
        } catch {
          map[config.configKey] = config.configValue;
        }
      } else {
        map[config.configKey] = config.configValue;
      }
    });
    return map;
  });

  const globalConfigMap = computed<ConfigMap>(() => {
    const map: ConfigMap = {};
    globalConfigs.value.forEach((config) => {
      if (config.configType === 'json') {
        try {
          map[config.configKey] = JSON.parse(config.configValue);
        } catch {
          map[config.configKey] = config.configValue;
        }
      } else {
        map[config.configKey] = config.configValue;
      }
    });
    return map;
  });

  // 获取配置值的方法
  const getConfigValue = (configKey: string, pageType: 'home' | 'about' | 'contact' | 'global' = 'global') => {
    let configMap: ConfigMap;
    switch (pageType) {
      case 'home':
        configMap = homeConfigMap.value;
        break;
      case 'about':
        configMap = aboutConfigMap.value;
        break;
      case 'contact':
        configMap = contactConfigMap.value;
        break;
      default:
        configMap = globalConfigMap.value;
    }
    return configMap[configKey] || '';
  };

  // 加载所有配置
  const loadAllConfigs = async () => {
    loading.value = true;
    try {
      const [homeRes, aboutRes, contactRes, globalRes] = await Promise.all([
        getHomeConfigs(),
        getAboutConfigs(),
        getContactConfigs(),
        getGlobalConfigs(),
      ]);

      homeConfigs.value = homeRes || [];
      console.log('homeConfigs.value', homeRes);

      aboutConfigs.value = aboutRes || [];
      contactConfigs.value = contactRes || [];
      globalConfigs.value = globalRes || [];
    } catch (error) {
      console.error('加载博客配置失败:', error);
    } finally {
      loading.value = false;
    }
  };

  // 获取首页配置数据
  const getHomeData = computed(() => ({
    title: getConfigValue('home_title', 'home') || 'ECHO - Java全栈开发工程师',
    subtitle: getConfigValue('home_subtitle', 'home') || '热爱编程，专注于Java后端开发和Spring生态',
    avatarUrl: getConfigValue('home_avatar_url', 'home') || 'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix',
    skills: getConfigValue('home_skills', 'home') || ['Java', 'Spring Boot', 'Spring Cloud', 'MySQL', 'Redis'],
  }));

  // 获取关于我页面配置数据
  const getAboutData = computed(() => ({
    name: getConfigValue('about_name', 'about') || 'ECHO',
    title: getConfigValue('about_title', 'about') || 'Java全栈开发工程师',
    description:
      getConfigValue('about_description', 'about') ||
      '热爱编程，专注于Java后端开发和Spring生态，拥有5年Java开发经验。擅长构建高性能、可扩展的企业级应用系统。',
    avatarUrl: getConfigValue('about_avatar_url', 'about') || 'https://api.dicebear.com/7.x/avataaars/svg?seed=Felix',
    backendSkills: getConfigValue('about_backend_skills', 'about') || [
      'Java',
      'Spring Boot',
      'Spring Cloud',
      'Spring Security',
      'MyBatis',
      'MyBatis Plus',
    ],
    databaseSkills: getConfigValue('about_database_skills', 'about') || ['MySQL', 'Oracle', 'MongoDB', 'Redis', 'Elasticsearch', 'PostgreSQL'],
    middlewareSkills: getConfigValue('about_middleware_skills', 'about') || ['RabbitMQ', 'Kafka', 'Docker', 'SVN', 'Git'],
    frontendSkills: getConfigValue('about_frontend_skills', 'about') || ['Vue.js', 'TypeScript', 'Ant Design', 'SCSS'],
    serverSkills: getConfigValue('about_server_skills', 'about') || ['Ubuntu', 'CentOS', 'RedHat', 'Nginx', 'Tomcat'],
  }));

  // 获取联系我页面配置数据
  const getContactData = computed(() => ({
    email: getConfigValue('contact_email', 'contact') || 'echo@echoreminis.top',
    github: getConfigValue('contact_github', 'contact') || 'Accompany-Z',
    wechat: getConfigValue('contact_wechat', 'contact') || 'Echo Reminis',
    wechatQr: getConfigValue('contact_wechat_qr', 'contact') || 'https://img.zwfcyy.top/echo/bolg-connect/wechat-w.png',
    collaborationAreas: getConfigValue('contact_collaboration_areas', 'contact') || [
      { icon: '🏢', title: '企业级应用开发', description: '大型企业系统架构设计与开发' },
      { icon: '🔧', title: '微服务架构设计', description: '分布式系统架构优化与重构' },
      { icon: '💡', title: '技术咨询顾问', description: '技术选型与架构设计咨询' },
      { icon: '🌟', title: '开源项目合作', description: '开源项目贡献与维护' },
    ],
  }));

  // 获取全局配置数据
  const getGlobalData = computed(() => ({
    siteName: getConfigValue('site_name', 'global') || 'ECHO Blog',
    siteDescription: getConfigValue('site_description', 'global') || 'Java全栈开发工程师的个人博客',
    siteKeywords: getConfigValue('site_keywords', 'global') || 'Java,Spring Boot,微服务,全栈开发',
    siteIcp: getConfigValue('site_icp', 'global') || '鲁ICP备2021039405号-1',
    siteCopyright: getConfigValue('site_copyright', 'global') || 'Copyright © 2024 Echo Reminis. All Rights Reserved.',
  }));

  return {
    loading,
    homeConfigs,
    aboutConfigs,
    contactConfigs,
    globalConfigs,
    homeConfigMap,
    aboutConfigMap,
    contactConfigMap,
    globalConfigMap,
    getConfigValue,
    loadAllConfigs,
    getHomeData,
    getAboutData,
    getContactData,
    getGlobalData,
  };
}

const skills = ref<any[]>([]);
export async function loadSkills() {
  const res = await fetchSkills();
  if (Array.isArray(res)) {
    skills.value = res;
  } else if (res && typeof res.configValue === 'string') {
    try {
      skills.value = JSON.parse(res.configValue);
    } catch {
      skills.value = [];
    }
  } else {
    skills.value = [];
  }
}
export function useSkills() {
  return { skills, loadSkills };
}
